package com.leen.service.impl;

import com.leen.common.vo.ResponseVO;
import com.leen.dto.AdminDTO;
import com.leen.entity.Admin;
import com.leen.repository.AdminRepository;
import com.leen.service.AdminService;
import com.leen.service.CrudService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.swing.plaf.SeparatorUI;
import java.util.ArrayList;
import java.util.List;

/**
 * 类说明
 *
 * @author admin
 * @date 2021-04-21
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class AdminServiceImpl extends CurdServiceImpl<Admin,Integer> implements AdminService {

    private AdminRepository adminRepository;

    @Autowired
    public void setAdminRepository(AdminRepository adminRepository) {
        this.adminRepository = adminRepository;
        //给父类赋值
        super.setCrudRepository(adminRepository);
    }

    @Override
    public ResponseVO search(AdminDTO adminDTO) {
       //分页页码
        Pageable pageable= PageRequest.of(adminDTO.getPageNumber()-1,  adminDTO.getPageSize());
        //最难构建查询对象
        Specification<Admin> specification=new Specification<Admin>() {
            @Override
            public Predicate toPredicate(Root<Admin> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> arr=new ArrayList<>();
                arr.add(criteriaBuilder.equal(  root.get("status"),  adminDTO.getStatus()));

                if(StringUtils.isNotBlank(adminDTO.getLoginName())){
                    arr.add(criteriaBuilder.like(  root.get("loginName"),  "%"+adminDTO.getLoginName()+"%"));
                }
                if(StringUtils.isNotBlank(adminDTO.getMobile())){
                    arr.add(criteriaBuilder.equal(  root.get("mobile"),  adminDTO.getMobile()));
                }
                return criteriaBuilder.and( arr.toArray(new Predicate[arr.size()]));
            }
        };
        //查询
        Page<Admin> page = this.adminRepository.findAll(specification, pageable);
        return new ResponseVO( page.getTotalElements(),  page.getContent() );
    }



}
